//
//  WPRightManagerViewController.m
//  ZhongChouPingTai
//
//  Created by WeiPan on 16/4/4.
//  Copyright © 2016年 WPJoe. All rights reserved.
//

#import "WPRightManagerViewController.h"
#import "WPDIYSegment.h"

#import "WPRightManageFooterView.h"
#import "WPRightManageUsableHeaderView.h"
#import "WPRightManageInvalidHeadView.h"

#import "WPRightManageUsableCell.h"
#import "WPRightManageInvalidCell.h"

#import "WPTansStyleAlertView.h"
#import "WPSigleTransPriceAlertView.h"
#import "WPTeamTransAlertView.h"

#import "WPRightManagerViewModel.h"
#import "WPRightManageDetailModel.h"
#import "WPTransRightManageHeadModel.h"


static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";

@interface WPRightManagerViewController ()<UITableViewDataSource, UITableViewDelegate, WPRightManageFooterViewDelegate, WPRightManageTableCellDelegate>
@property (nonatomic, strong) WPDIYSegment * segment;/**< 自定义分段控件 */
@property (nonatomic, strong) UILabel * noDataLabel;/**< 无数据提示 */
@property (nonatomic, strong) UITableView * rightTableView;/**< 权益列表 */
@property (nonatomic, strong) NSMutableArray * usableRightManageArr;/**< 权益管理有效数据源 */
@property (nonatomic, strong) NSMutableArray * invalidRightManageArr;/**< 失效数据源 */
@property (nonatomic, strong) NSMutableArray * usableRightMangeHeadViews;/**< 可用头部视图数组 */
@property (nonatomic, strong) NSMutableArray * invaliManageHeadView;/**< 失效头部视图数组 */

@property (nonatomic, strong) NSMutableArray * usableRightManageFootViews;/**< 尾部视图数组 */
@property (nonatomic, strong) NSMutableArray * planTransTickeArr;/**< 准备转卖数组 */
@property (nonatomic, assign) BOOL isContract;/**< 收缩 */
@property (nonatomic, assign) NSInteger currentPage;/**< 当前页码 */
@property (nonatomic, assign) NSInteger totalsPages;/**< 总页码 */
@property (nonatomic, strong) UILabel * noMoreLabel;/**< 没有说明 */

- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */
- (void)refreshData;/**< 刷新数据 */


@end

@implementation WPRightManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}
#pragma mark - init
- (void)initializeDataSource {
    self.currentPage = 1;
    self.totalsPages = 1;
    self.usableRightManageArr = [NSMutableArray arrayWithCapacity:0];
    self.usableRightMangeHeadViews = [NSMutableArray arrayWithCapacity:0];
    self.usableRightManageFootViews = [NSMutableArray arrayWithCapacity:0];
    self.invalidRightManageArr = [NSMutableArray arrayWithCapacity:0];
    self.invaliManageHeadView = [NSMutableArray arrayWithCapacity:0];
    self.planTransTickeArr = [NSMutableArray arrayWithCapacity:0];
}
- (void)initializeUserInterface {
    if (!_model) {
        [self.view addSubview:self.segment];
    }
    self.navigationController.navigationBarHidden = NO;
    [_segment setSegmentOriginPoint:CGPointMake(0, navBar_Fheight)];
    [self.view addSubview:self.rightTableView];
    __weak typeof(self)weakself = self;
    _rightTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        [weakself refreshData];
    }];
    _rightTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _currentPage++;
        [weakself refreshData];
    }];
    [_rightTableView.header beginRefreshing];
    _segment.indexBlock = ^(NSInteger index, NSString * title) {
        if (weakself.noMoreLabel.superview) {
            [weakself.noMoreLabel removeFromSuperview];
        }
        _currentPage = 1;
        _totalsPages = 1;
        [NetWorkingManager cancelAllOperations];
        [weakself.rightTableView reloadData];
        [weakself.rightTableView.header endRefreshing];
        [weakself.rightTableView.header beginRefreshing];
    };
}
#pragma mark - 刷新数据

- (void)refreshData {
    if (_currentPage > _totalsPages) {
        [_rightTableView.footer noticeNoMoreData];
        return;
    }
    __weak typeof(self)weakself = self;
    [WPRightManagerViewModel getTransedTicketListWithPageNumber:_currentPage andIsUsable:_segment.selectedIndex andWithOrderID:_model.orderId andSuccessBlock:^(NSMutableArray *succ, NSInteger totalPages) {
        _totalsPages = totalPages;
        if (_currentPage == 1 && !_segment.selectedIndex) {
            if (_usableRightManageArr.count ) {
                [_usableRightManageArr removeAllObjects];
            }
            for (id obj in succ) {
                [_usableRightManageArr addObject:obj];
            }
        }
        if (_currentPage == 1 && _segment.selectedIndex) {
            if (_invalidRightManageArr.count) {
                [_invalidRightManageArr removeAllObjects];
            }
            for (id obj in succ) {
                [_invalidRightManageArr addObject:obj];
            }
        }
        if (weakself.segment.selectedIndex && weakself.invaliManageHeadView.count &&weakself.noMoreLabel.superview) {
            [weakself.noMoreLabel removeFromSuperview];
        }
        if (!weakself.segment.selectedIndex && weakself.usableRightManageArr.count && weakself.noMoreLabel.superview) {
            [weakself.noMoreLabel removeFromSuperview];
        }

        [_rightTableView reloadData];
        [weakself congigHeadViewWithHeadModel];
        [weakself configFootView];
        [weakself endRefresh];
    } andFailureBlock:^(NSString *fail) {
        if (weakself.segment.selectedIndex && !weakself.invaliManageHeadView.count &&!weakself.noMoreLabel.superview) {
            [weakself.view addSubview:weakself.noMoreLabel];
        }
        if (!weakself.segment.selectedIndex && !weakself.usableRightManageArr.count && !weakself.noMoreLabel.superview) {
            [weakself.view addSubview:weakself.noMoreLabel];
        }
        if (_currentPage == 1 && [fail isEqualToString:@"暂无数据"]) {
            [weakself.usableRightManageArr removeAllObjects];
            [weakself.invalidRightManageArr removeAllObjects];
            [weakself.view addSubview:weakself.noDataLabel];
        }
        [_rightTableView reloadData];
        [weakself endRefresh];
    }];
}
- (void)endRefresh {
    [_rightTableView.header endRefreshing];
    [_rightTableView.footer endRefreshing];
}
#pragma mark - 协议UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _segment.selectedIndex ? _invalidRightManageArr.count : _usableRightManageArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _segment.selectedIndex ? [_invalidRightManageArr[section][1] count]:_isContract ? 0:[_usableRightManageArr[section][1] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_segment.selectedIndex) {
        WPRightManageInvalidCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (!cell) {
            cell = [[WPRightManageInvalidCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kUITableViewCellIdentifier];
        }
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setModel:_invalidRightManageArr[indexPath.section][1][indexPath.row]];
        return cell;
    }
    WPRightManageUsableCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[WPRightManageUsableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.isDetail = _model ? YES : NO;
    [cell setModel:_usableRightManageArr[indexPath.section][1][indexPath.row]];
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (_model || [[UserModel defaultUser].memberRankNumber integerValue] == 1) {
        return 10;
    }
    return _segment.selectedIndex ? 10 :  _isContract ? 80 *DHFlexibleHorizontalMutiplier() : 110*DHFlexibleHorizontalMutiplier();
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 175*DHFlexibleHorizontalMutiplier();
}
//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30*DHFlexibleHorizontalMutiplier();
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return _segment.selectedIndex ? _invaliManageHeadView[section]: _usableRightMangeHeadViews[section];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (_model || _segment.selectedIndex) {
        UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 10)];
        footView.backgroundColor = [UIColor whiteColor];
        return footView;
    }
    return _usableRightManageFootViews[section];
}
#pragma mark - private protocol
- (void)actionOnEditBtnWithDetailModel:(WPRightManageDetailModel *)model andWithIsAdd:(BOOL)isAdd {
    if (isAdd) {
        [_planTransTickeArr addObject:model];
    } else {
        if ([_planTransTickeArr containsObject:model]) {
            [_planTransTickeArr removeObject:model];
        }
    }
}
- (void)actionOnTransBtn {
    if (!_planTransTickeArr.count) {
        [self initializeAlertControllerWithMessageAndDismiss:@"请先选择您想转让的票"];
        return;
    }
    __weak typeof(self)weakself = self;
    [WPTansStyleAlertView showViewWithSize:CGRectMake(20*DHFlexibleHorizontalMutiplier(), 110*DHFlexibleHorizontalMutiplier(), 270*DHFlexibleHorizontalMutiplier(), 190*DHFlexibleHorizontalMutiplier()) andWithTitle:@"请选择转让方式" WithComplete:^(NSString *result) {
        if ([result isEqualToString:@"单个转让"]) {
            [weakself alertSigleTransPriceView];
        } else {
            [weakself alertTeamTransPriceView];
        }
    }];


}
-(void)actionOnSpreadBtn:(BOOL)isContract{
    self.isContract = isContract;
  [_rightTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}
- (void)congigHeadViewWithHeadModel {
    if (_segment.selectedIndex) {
        if (self.invaliManageHeadView.count) {
            [_invaliManageHeadView removeAllObjects];
        }
        for (int i = 0; i < _invalidRightManageArr.count; i++) {
            WPRightManageInvalidHeadView * view = [[WPRightManageInvalidHeadView alloc]initWithHeadModel:_invalidRightManageArr[i][0]];
            [_invaliManageHeadView addObject:view];
        }
        return;
    }
    if (self.usableRightManageFootViews.count) {
        [_usableRightMangeHeadViews removeAllObjects];
    }
    for (int i = 0; i < _usableRightManageArr.count; i++) {
        WPRightManageUsableHeaderView * view = [[WPRightManageUsableHeaderView alloc]initWithHeadModel:_usableRightManageArr[i][0]];
        [_usableRightMangeHeadViews addObject:view];
    }
}
- (void)configFootView {
    if (self.usableRightManageFootViews.count) {
        [_usableRightManageFootViews removeAllObjects];
    }
    for (int i = 0; i < _usableRightManageArr.count; i++) {
        WPRightManageFooterView * view = [[WPRightManageFooterView alloc]init];
        view.delegate = self;
        [_usableRightManageFootViews addObject:view];
    }
}
#pragma mark - private methods
- (void)alertSigleTransPriceView {
    __weak typeof(self)weakself = self;
    [WPSigleTransPriceAlertView showViewWithSize:CGRectMake(20*DHFlexibleHorizontalMutiplier(), 110*DHFlexibleHorizontalMutiplier(), 270*DHFlexibleHorizontalMutiplier(), 270*DHFlexibleHorizontalMutiplier()) andWithTitle:@"转让权益" andWithDatasource:_planTransTickeArr andWithComplete:^(NSArray *result) {
        if (result.count) {
            [weakself transSigleTicketWithTransPrice:result];
        } else {
            [weakself initializeAlertControllerWithMessageAndDismiss:@"请确认已填写完整"];
        }
    }];
}
- (void)alertTeamTransPriceView {
    __weak typeof(self)weakself = self;
    NSMutableArray * positionArr = [NSMutableArray arrayWithCapacity:0];
    for (WPRightManageDetailModel * model in _planTransTickeArr) {
        [positionArr addObject:model.ticketId];
    }
    [WPTeamTransAlertView showViewWithSize:CGRectMake(20*DHFlexibleHorizontalMutiplier(), 110*DHFlexibleHorizontalMutiplier(), 270*DHFlexibleHorizontalMutiplier(), 300) andWithTitle:@"组合转卖" andWithDatasource:positionArr andWithComplete:^(NSString *result) {
        [weakself transTeamTicketWithTransPrice:result];
    }];
}
- (void)transSigleTicketWithTransPrice:(NSArray *)ticketIdsAndPrice {
    __weak typeof(self)weakself = self;
    [WPRightManagerViewModel transTicketWithGoogId:@(77) andWithSaleType:@(0) andWithProductIds:ticketIdsAndPrice andSalePrice:nil andWithSuccessBlock:^(NSString *succ) {
        [weakself.rightTableView.header beginRefreshing];
        [weakself.planTransTickeArr removeAllObjects];
    } andWithFailureBlock:^(NSString *failure) {
        [weakself initializeAlertControllerWithMessageAndDismiss:@"转让提交失败"];
        [weakself.rightTableView.header beginRefreshing];
        [weakself.planTransTickeArr removeAllObjects];
    }];
}
- (void)transTeamTicketWithTransPrice:(NSString *)price {
    NSMutableArray * ticketIds = [NSMutableArray arrayWithCapacity:0];
    for (WPRightManageDetailModel * model in _planTransTickeArr) {
        [ticketIds addObject:model.ticketId];
    }
    __weak typeof(self)weakself = self;
    [WPRightManagerViewModel transTicketWithGoogId:@(77) andWithSaleType:@(1) andWithProductIds:ticketIds andSalePrice:price andWithSuccessBlock:^(NSString *succ) {
        [weakself.rightTableView.header beginRefreshing];
        [weakself.planTransTickeArr removeAllObjects];
    } andWithFailureBlock:^(NSString *failure) {
        [weakself initializeAlertControllerWithMessageAndDismiss:@"转让提交失败"];
    }];

}
#pragma mark - getter
- (WPDIYSegment *)segment {
    if (!_segment) {
        _segment = ({
            WPDIYSegment * seg = [[WPDIYSegment alloc]initWithTitles:@[@"可用", @"失效"]];
            seg.backgroundColor = [UIColor whiteColor];
            seg;
        });
    }
    return _segment;
}
- (UITableView *)rightTableView {
    if (!_rightTableView) {
        _rightTableView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:CGRectMake(10*DHFlexibleHorizontalMutiplier(), 105*DHFlexibleHorizontalMutiplier(), 300*DHFlexibleHorizontalMutiplier(), SCREEN_SIZE.height - 105*DHFlexibleHorizontalMutiplier()) style:UITableViewStyleGrouped];
            if (_model) {
                tableview.frame = CGRectMake(10*DHFlexibleHorizontalMutiplier(), 75*DHFlexibleHorizontalMutiplier(), 300*DHFlexibleHorizontalMutiplier(), SCREEN_SIZE.height - 75*DHFlexibleHorizontalMutiplier());
            }
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.layer.cornerRadius = 5*DHFlexibleHorizontalMutiplier();
            tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
            tableview.backgroundColor = [UIColor clearColor];
            tableview;
        });
    }
    return _rightTableView;
}
- (UILabel *)noMoreLabel {
    if (!_noMoreLabel) {
        _noMoreLabel = ({
            UILabel * lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, 30*DHFlexibleHorizontalMutiplier())];
            lab.center = self.view.center;
            lab.font = [UIFont systemFontOfSize:12*DHFlexibleHorizontalMutiplier()];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.text = @"暂无数据";
            lab;
        });
    }
    return _noMoreLabel;
}
@end
